import React, { useContext, useEffect } from 'react';
import { Dropdown, Menu, Message, Button } from '@arco-design/web-react';
import {
  IconSettings,
  IconPoweroff,
  IconUser,
} from '@arco-design/web-react/icon';
import { useSelector, useDispatch } from 'react-redux';
import { GlobalState } from '@/store';
import { GlobalContext } from '@/context';
import useLocale from '@/utils/useLocale';
import Settings from '../Settings';
import styles from './style/index.module.less';
import useStorage from '@/utils/useStorage';
import { generatePermission } from '@/routes';
import { logout } from '@/utils/login/index';

function Navbar({ show }: { show: boolean }) {
  const t = useLocale();
  const userInfo = useSelector((state: GlobalState) => state.userInfo);
  const dispatch = useDispatch();

  const [_, setUserStatus] = useStorage('userStatus');
  const [role, setRole] = useStorage('userRole', 'admin');
  const [userName, setUserName] = useStorage('userName', '');

  const { setLang, lang, theme, setTheme } = useContext(GlobalContext);

  function onMenuItemClick(key) {
    if (key === 'logout') {
      logout();
    } else {
      Message.info(`You clicked ${key}`);
    }
  }

  useEffect(() => {
    setTheme('light');
    dispatch({
      type: 'update-userInfo',
      payload: {
        userInfo: {
          ...userInfo,
          permissions: generatePermission(role),
        },
      },
    });
  }, [role]);

  if (!show) {
    return (
      <div className={styles['fixed-settings']}>
        <Settings
          trigger={
            <Button icon={<IconSettings />} type="primary" size="large" />
          }
        />
      </div>
    );
  }

  const droplist = (
    <Menu onClickMenuItem={onMenuItemClick}>
      <Menu.Item key="logout">
        <IconPoweroff className={styles['dropdown-icon']} />
        {t['navbar.logout']}
      </Menu.Item>
    </Menu>
  );

  return (
    <div className={styles.navbar}>
      <div className={styles.left}>
        <div className={styles.logo}>
          <div className={styles['logo-name']}>教育后台管理系统</div>
        </div>
      </div>
      <ul className={styles.right}>
        {userInfo && (
          <li>
            <Dropdown droplist={droplist} position="br">
              {!!userName ? (
                <span style={{ cursor: 'pointer' }}> {userName}</span>
              ) : (
                <IconUser />
              )}
            </Dropdown>
          </li>
        )}
      </ul>
    </div>
  );
}

export default Navbar;
